const router = require("express").Router();
const Article = require("../../models/article");

router.get("/", async (req, res) => {
  const page = req.query.page * 1 || 1;
  const per = req.query.per * 1 || 10;
  const queryBuild = {};
  if (req.query.title) {
    queryBuild.title = new RegExp(req.query.title);
  }
  const articles = await Article.find(queryBuild)
    .skip((page - 1) * per)
    .limit(per)
    .sort({ _id: -1 });
  const totals = await Article.count(queryBuild);
  res.render("admin/articles/index", {
    articles, // 列表数据
    totals, // 总数量
    page,
    pages: Math.ceil(totals / per), // 总页数
  });
});

router.get("/new", (req, res) => {
  res.render("admin/articles/new");
});

router.post("/create", async (req, res) => {
  const article = new Article(req.body);
  await article.save();
  res.redirect("/admin/articles");
});

router.get("/edit/:id", async (req, res) => {
  const article = await Article.findById(req.params.id);
  res.render("admin/articles/edit", {
    article,
  });
});

router.post("/modify/:id", async (req, res) => {
  await Article.findByIdAndUpdate(req.params.id, req.body);
  res.redirect("/admin/articles");
});

router.post("/remove", async (req, res) => {
  await Article.findByIdAndDelete(req.body.id);
  res.redirect("/admin/articles");
});

module.exports = router;
